package cn.stylefeng.guns.modular.controller;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.entity.IdjBanner;
import cn.stylefeng.guns.modular.entity.responseVo.MessageVo;
import cn.stylefeng.guns.modular.service.IIdjBannerService;
import cn.stylefeng.guns.modular.util.HttpClientUtil;
import cn.stylefeng.guns.modular.util.json.JsonUtils;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;

/**
 * <p>
 * 轮播图 前端控制器
 * </p>
 *
 * @author TANGWJ
 * @since 2020-07-07
 */
@Controller
@RequestMapping("/modular/banner")
public class IdjBannerController {

	private static String PREFIX = "/banner/";

	private static final int SHORT_MAX = 65536;

	private static int counter = -1;

	@Autowired
	private IIdjBannerService service;

	/**
	 * 跳转到用户的首页
	 */
	@RequestMapping
	public String index() {
		return PREFIX + "banner.html";
	}

	@RequestMapping("details/{bannerId}")
	public ModelAndView detail(@PathVariable Long bannerId) {
		ModelAndView index = service.edit(bannerId);
		index.setViewName(PREFIX + "banner_details.html");
		return index;
	}
	
	@RequestMapping("edit/{bannerId}")
	public ModelAndView edit(@PathVariable Long bannerId) {
		ModelAndView index = service.edit(bannerId);
		index.setViewName(PREFIX + "banner_edit.html");
		return index;
	}

	@RequestMapping("/add")
	public String add() {
		return PREFIX + "banner_add.html";
	}

	/**
	 * 查询注册用户列表
	 */
	@ResponseBody
	@GetMapping("list")
	public LayuiPageInfo list(Integer bannerType) {
		// 获取分页参数
		Page page = LayuiPageFactory.defaultPage();
		return service.getList(page, bannerType);
	}

	@RequestMapping("/update")
	@ResponseBody
	public ResponseData update(@RequestBody IdjBanner banner) {
		if (ToolUtil.isEmpty(banner.getBannerId())) {
			throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
		}
		banner.setUpdateTime(new Date());
		service.setStatus(banner);
		return ResponseData.success();
	}

	@RequestMapping("/insert")
	@ResponseBody
	public ResponseData insert(@RequestBody IdjBanner banner) {
		banner.setBannerId(nextId());
		banner.setCreateTime(LocalDateTime.now());
		banner.setUpdateTime(new Date());
		service.insert(banner);
		return ResponseData.success();
	}

	@RequestMapping("/delete/{bannerId}")
	@ResponseBody
	public ResponseData delete(@PathVariable Long bannerId) {
		if (ToolUtil.isEmpty(bannerId)) {
			throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
		}
		service.delete(bannerId);
		return ResponseData.success();
	}
	
	/**
	 * 上传图片
	 *
	 * @author fengshuonan
	 * @Date 2018/12/24 22:44
	 */
	@RequestMapping(method = RequestMethod.POST, path = "/upload")
	@ResponseBody
	public String upload(@RequestPart("file") MultipartFile picture,HttpServletRequest request) {
		String result = null;
		try {
			 // 获取文件名
	        String fileName = picture.getOriginalFilename();
	        // 获取文件后缀
	        String prefix=fileName.substring(fileName.lastIndexOf("."));
	        // 用uuid作为文件名，防止生成的临时文件重复
	        final File excelFile = File.createTempFile(UUID.randomUUID().toString(), prefix);
	        // MultipartFile to File
	        picture.transferTo(excelFile);
			String image = HttpClientUtil.uploadImage("https://www.idjglobalapp.com/app-servce/v1/api/upload", "富文本图片上传", excelFile);
			MessageVo vo = JsonUtils.toObject(image, MessageVo.class);
			Map<String,Object> map = new HashMap<String,Object>();
		    Map<String,Object> map2 = new HashMap<String,Object>();
		    map.put("code",0);//0表示成功，1失败
		    map.put("msg",vo.getMsg());//提示消息
		    map.put("data",map2);
		    map2.put("src",vo.getData());//图片url
		    map2.put("title",fileName);//图片名称，这个会显示在输入框里
		    result = new JSONObject(map).toString();
		    deleteFile(excelFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	    return result;
	}

	public static synchronized long nextId() {
		long now = System.currentTimeMillis();
		if (counter == -1) {
			long seed = now ^ Thread.currentThread().getId();
			Random rnd = new Random(Long.hashCode(seed));
			counter = rnd.nextInt(SHORT_MAX);
		}
		long id = (now << 16) | counter;
		counter = (counter + 1) % SHORT_MAX;
		return id;
	}
	
	 /**  
     * 删除  
     *   
     * @param files  
     */  
    private void deleteFile(File... files) {  
        for (File file : files) {  
            if (file.exists()) {  
                file.delete();  
            }  
        }  
    }
}
